module IPFS.Client.Command.Object (
  stat,
  StatInfo(..)
) where
import Prelude

import Data.Argonaut (class DecodeJson, Json, decodeJson, fromString)
import Data.Argonaut.Decode ((.:))
import Data.Either (Either)
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)
import Data.Maybe (Maybe(..))
import Effect.Aff (Aff)
import Foreign.Object as O
import IPFS.Client (Client)
import IPFS.Client.Command (Command, defCommand)
import IPFS.Client.Utils.SendRequest (execJsonCommand)

--------------------------------------stat--------------------------
newtype StatInfo = StatInfo {
  hash::String,
  numLinks::Int,
  blockSize::Int,
  linksSize::Int,
  dataSize::Int,
  cumulativeSize::Int
}

derive instance genericStatInfo :: Generic StatInfo _
instance showVersion :: Show StatInfo where
  show s = genericShow s

instance versionDecodeJson :: DecodeJson StatInfo where
  decodeJson::Json -> Either String StatInfo
  decodeJson json = do
   dJson::O.Object Json <- decodeJson json
   hash             <- dJson .: "Hash"
   numLinks         <- dJson .: "NumLinks"
   blockSize        <- dJson .: "BlockSize"
   linksSize         <- dJson .: "LinksSize"
   dataSize         <- dJson .: "DataSize"
   cumulativeSize   <- dJson .: "CumulativeSize"
   pure $ StatInfo {hash:hash,
                    numLinks:numLinks,
                    blockSize:blockSize,
                    linksSize:linksSize,
                    dataSize:dataSize,
                    cumulativeSize:cumulativeSize}

statCommand::String -> Command
statCommand hash = defCommand {path = "object/stat", args = Just [fromString hash] ,qs = O.empty}

stat::Client -> String -> Aff (Either String StatInfo)
stat client hash = execJsonCommand client $ statCommand hash